import {
    toast
} from '../../../utils/util'
import {
    establishCase
} from '../../api/insurance'
import global from '../../../utils/global'
import user from '../../../utils/user'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        ssq: '',
        outDangerUserId: '', // 出保人id
        outDangerPhone: '',
        outDangerUserName: '',
        comboName: '',
        outDangerDate: '',
        reportPhone: '', // 报案人手机号
        hurtStatus: '1', // 1是 2不是
        accidentType: '1', // 1意外 2工伤
        outDangerPlace: '', // '出险地点'
        outDangerPlacedtl: '', // '出险地点'
        accidentDetails: '', // 事故经过
        textSwitch: true,
        idCardNo: '', // 出险人身份证
        params: {
            photos: [], // 图片视频
        },
        isVideo: false, // 只有上传的文件里有一个视频才可通过
        temporary: [], // 暂时存储视频图片
        visitHospital: '' // 就诊医院地点
    },
    unique(arr) {
        for (var i = 0; i < arr.length; i++) {
            for (var j = i + 1; j < arr.length; j++) {
                if (arr[i] == arr[j]) { // 第一个等同于第二个，splice方法删除第二个
                    arr.splice(j, 1)
                    j--
                }
            }
        }
        return arr
    },
    bindPickerAddress(e) {
        console.log(e, 'gsdhuhug')
        this.setData({
            ssq: this.unique(e.detail.value).join('')
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function () {
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.on('init', (data) => {
            this.setData({
                outDangerPhone: data.phone,
                outDangerUserName: data.userName,
                comboName: data.comboName,
                outDangerDate: data.date,
                recordId: data.id,
                outDangerUserId: data.userId,
                reportPhone: user.phoneNum,
                idCardNo: data.idCardNo
            })
        })

    },

    onHurtStatus(event) {
        console.log(event)
        const {
            type
        } = event.currentTarget.dataset
        this.setData({
            hurtStatus: type
        })
    },
    onAccidentType(event) {
        const {
            type
        } = event.currentTarget.dataset
        this.setData({
            accidentType: type
        })
    },
    onReportPhoneInput(event) {
        this.setData({
            reportPhone: event.detail.value
        })
    },
    onDangerPhoneInput(event) {
        this.setData({
            outDangerPhone: event.detail.value
        })
    },
    onOutDangerPlaceInput(event) {
        this.setData({
            outDangerPlacedtl: event.detail.value
        })
    },
    onVisitHospitalInput(event) {
        this.setData({
            visitHospital: event.detail.value
        })
    },
    onAccidentDetailsInput(event) {
        this.setData({
            accidentDetails: event.detail.value
        }, () => {
            if (this.data.accidentDetails) {
                this.setData({
                    textSwitch: false
                })
            } else {
                this.setData({
                    textSwitch: true
                })
            }
        })
    },
    async onAddInsurance() {
        console.log(this.data)
        console.log(this.data.temporary, '视频列表')
        this.data.temporary.forEach(item => {
            if (item.fileType === 'video') {
                this.setData({
                    isVideo: true
                })
            }
        })
        if (!this.data.outDangerDate) {
            toast('请填写出险日期')
            return
        }
        if (!this.data.outDangerPhone) {
            toast('请填写出险人手机号')
            return
        }
        if (!this.data.reportPhone) {
            toast('请填写报案人手机号')
            return
        }
        if (this.data.temporary.length > 3) {
            toast('最多只支持上传三个')
            return
        }
        if (!this.data.ssq) {
            toast('请填写出险省市区')
            return
        }
        if (!this.data.outDangerPlacedtl) {
            toast('请填写详细出险地点')
            return
        }
        if (!this.data.visitHospital) {
            toast('请填写就诊医院')
            return
        }
        if (!this.data.accidentDetails) {
            toast('请填写出险经过')
            return
        }
        if (!this.data.isVideo) {
            toast('请至少上传一个视频')
            return
        }
        console.log(this.data, 'this.data')
        this.filePush(this.data.temporary)
    },
    // 上传图片
    upload() {
        const t = this
        wx.chooseMedia({
            count: 3,
            // maxDuration: 20,
            sizeType: ['compressed'], // 压缩
            success(res) {
                console.log(res, 'res')

                if (res.tempFiles[0].duration > 20) {
                    toast('请将视频时长控制在20秒以内')
                    return
                }
                if (res.tempFiles[0].fileType === 'video' && res.tempFiles[0].size > 30 * 1024 * 1024) {
                    toast('请将视频大小控制在30MB以内')
                    return
                }
                if (t.data.temporary.length >= 3) {
                    toast('最多上传三个视频或图片')
                    return
                }
                console.log(res.tempFiles)
                const arr = []
                arr.push(...t.data.temporary)
                arr.push(res.tempFiles[0])
                arr.forEach((item, index) => {
                    let fileType = 'image'
                    if (
                        /(mp4|flv|mov|wmv|avi|mpeg|rmvb)$/.test(item.tempFilePath)
                    ) {
                        fileType = 'video'
                    }
                    console.log(fileType, 'type')
                    arr[index].fileType = fileType
                    console.log(arr[index].fileType, 'fileType')
                })
                t.setData({
                    temporary: arr
                })
                console.log(t.data.temporary, 'temporary暂时')
            }
        })
    },
    // 文件批量上传并保存
    async filePush(tempFiles) {
        const t = this
        const files = []
        files.push(...this.data.params.photos)
        // if (tempFiles.fileType !== 'video') {
        //     files.push(tempFiles)
        // }
        wx.showLoading({
            title: '报案上传中',
            mask: true
        })
        let promise = Promise.all(tempFiles.map((item) => {
            return new Promise((resolve) => {
                wx.uploadFile({
                    url: global.baseUrl + '/api/v1/pay/wesure-report-case/upload',
                    filePath: item.tempFilePath,
                    name: 'file',
                    success(res) {
                        console.log('上传成功', res.data)
                        resolve(res.data)

                    },
                })
            })
        }))
        promise.then(res => {
            console.log(res, 'resresres')
            const files = []
            res.forEach(item => {
                const url = JSON.parse(item).data.fileUrl
                const size = JSON.parse(item).data.fileSize
                let type = 'photo'
                if (
                    /(mp4|flv|mov|wmv|avi|mpeg|rmvb)$/.test(url.toLowerCase())
                ) {
                    console.log(type)
                    type = 'video'
                }
                files.push({
                    fileUrl: url,
                    fileType: type,
                    fileSize: size
                })
                console.log('提交成功0')
                wx.hideLoading()
            })
            t.setData({
                ['params.photos']: files,
                ['outDangerPlace']: t.data.ssq + t.data.outDangerPlacedtl
            })
            establishCase(t.data).then(() => {
                toast('提交成功')
                wx.navigateTo({
                    url: '/pages/success/success?title=申请成功&content=请等待上级审批&opinion=0&back=home'
                })
                // wx.navigateBack({
                //     delta:2
                // })
            })
        })

    },
    onDelete(event) {
        let {
            index
        } = event.currentTarget.dataset
        this.data.temporary.splice(index, 1)
        this.setData({
            temporary: this.data.temporary
        })
    },
    onPreview(event) {
        const {
            url
        } = event.currentTarget.dataset
        wx.previewImage({
            urls: [url]
        })
    },
    onPlay(event) {
        console.log(event.currentTarget.id)
        // 获取 video 上下文 videoContext 对象
        this.videoContext = wx.createVideoContext(event.currentTarget.id, this)
        // 进入全屏状态
        this.videoContext.requestFullScreen()
        return 0
    },
})